import { Tooltip } from 'antd';
import { useCallback, useMemo } from 'react';
import { Connection, Handle, Position } from 'reactflow';
import { useContextSelector } from 'use-context-selector';

import { SvgIcon } from '@/components/icon';
import { t } from '@/locales/i18n';
import { NodeOutputKeyEnum } from '@/types/workflow/constant';

import { WorkflowContext } from '../../../../context';

const handleSize = '16px';

type ToolHandleProps = {
  nodeId: string;
  show: boolean;
};
export const ToolTargetHandle = ({ show, nodeId }: ToolHandleProps) => {
  const connectingEdge = useContextSelector(WorkflowContext, (ctx) => ctx.connectingEdge);
  const edges = useContextSelector(WorkflowContext, (v) => v.edges);

  const handleId = NodeOutputKeyEnum.selectedTools;

  const connected = edges.some((edge) => edge.target === nodeId && edge.targetHandle === handleId);

  // if top handle is connected, return null
  const showHandle = connectingEdge
    ? show && connectingEdge.handleId === NodeOutputKeyEnum.selectedTools
    : connected;

  const Render = useMemo(() => {
    return (
      <Handle
        style={{
          borderRadius: '0',
          backgroundColor: 'transparent',
          border: 'none',
          width: handleSize,
          height: handleSize,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          top: '-8px',
          ...(showHandle ? {} : { visibility: 'hidden' }),
        }}
        type="target"
        id={handleId}
        position={Position.Top}
        isConnectableEnd={showHandle}
      >
        <div className="pointer-events-none flex h-[16px] w-[16px] items-center justify-center rounded-full border-[1px] border-solid border-@brand-color-hover bg-white">
          <SvgIcon
            className="pointer-events-none"
            icon="add"
            color="var(--brand-color)"
            size={12}
          />
        </div>
      </Handle>
    );
  }, [handleId, showHandle]);

  return Render;
};

export const ToolSourceHandle = () => {
  const setEdges = useContextSelector(WorkflowContext, (v) => v.setEdges);

  /* onConnect edge, delete tool input and switch */
  const onConnect = useCallback(
    (e: Connection) => {
      setEdges((edges) =>
        edges.filter((edge) => {
          if (edge.target !== e.target) return true;
          if (edge.targetHandle === NodeOutputKeyEnum.selectedTools) return true;
          return false;
        }),
      );
    },
    [setEdges],
  );

  const Render = useMemo(() => {
    return (
      <Tooltip title={t('core.workflow.tool.Handle')}>
        <Handle
          style={{
            borderRadius: '0',
            backgroundColor: 'transparent',
            border: 'none',
            width: handleSize,
            height: handleSize,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            bottom: '-10px',
          }}
          type="source"
          id={NodeOutputKeyEnum.selectedTools}
          position={Position.Bottom}
          onConnect={onConnect}
        >
          <div className="pointer-events-none flex h-[16px] w-[16px] items-center justify-center rounded-full border-[1px] border-solid border-@brand-color-hover bg-white">
            <SvgIcon
              className="pointer-events-none"
              icon="add"
              color="var(--brand-color)"
              size={12}
            />
          </div>
        </Handle>
      </Tooltip>
    );
  }, [onConnect]);

  return Render;
};
